import 'package:blurb/common/models/user.dart';
import 'package:blurb/common/services/user_service.dart';
import 'package:blurb/common/values/images.dart';
import 'package:mobx/mobx.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:flutter/material.dart';

// 包含生成的代码部分
part 'user_store.g.dart';

// 使用命令生成代码：flutter packages pub run build_runner build
class UserStore = _UserStore with _$UserStore;

abstract class _UserStore with Store {
  @observable
  User? currentUser;

  @observable
  bool isLoading = false;

  @action
  Future<void> init() async {
    isLoading = true;
    try {
      // 初始化默认用户
      await UserService.initDefaultUsers();
      // 检查是否有已登录用户
      currentUser = await UserService.getCurrentUser();
    } finally {
      isLoading = false;
    }
  }

  @action
  Future<bool> login(String username, String password) async {
    isLoading = true;
    try {
      if (username.isEmpty || password.isEmpty) {
        Fluttertoast.showToast(
          msg: "username or password is empty",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          backgroundColor: Colors.red,
          textColor: Colors.white,
        );
        return false;
      }

      final user = await UserService.login(username, password);
      if (user != null) {
        currentUser = user;
        Fluttertoast.showToast(
          msg: "login success",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          backgroundColor: Colors.green,
          textColor: Colors.white,
        );
        return true;
      } else {
        Fluttertoast.showToast(
          msg: "username or password is wrong",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          backgroundColor: Colors.red,
          textColor: Colors.white,
        );
        return false;
      }
    } finally {
      isLoading = false;
    }
  }

  @action
  Future<bool> register(String username, String password, String confirmPassword, String nickname) async {
    isLoading = true;
    try {
      // 验证输入
      if (username.isEmpty || password.isEmpty || confirmPassword.isEmpty || nickname.isEmpty) {
        Fluttertoast.showToast(
          msg: "all fields cannot be empty",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          backgroundColor: Colors.red,
          textColor: Colors.white,
        );
        return false;
      }

      if (password != confirmPassword) {
        Fluttertoast.showToast(
          msg: "the two passwords are inconsistent",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          backgroundColor: Colors.red,
          textColor: Colors.white,
        );
        return false;
      }

      // 获取所有用户，确定新用户ID
      final users = await UserService.getAllUsers();
      final newUserId = users.isEmpty ? 1 : users.map((user) => user.id).reduce((a, b) => a > b ? a : b) + 1;

      // 创建新用户
      final newUser = User(
        id: newUserId,
        username: username,
        password: password,
        nickname: nickname,
        avatar: MIP.avatar, // 默认头像
        sign: 'Sunscreen enthusiast', // 默认签名
      );

      // 注册新用户
      final success = await UserService.register(newUser);
      if (success) {
        Fluttertoast.showToast(
          msg: "register success",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          backgroundColor: Colors.green,
          textColor: Colors.white,
        );
        return true;
      } else {
        Fluttertoast.showToast(
          msg: "username already exists",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          backgroundColor: Colors.red,
          textColor: Colors.white,
        );
        return false;
      }
    } finally {
      isLoading = false;
    }
  }

  @action
  Future<void> logout() async {
    isLoading = true;
    try {
      await UserService.logout();
      currentUser = null;
      Fluttertoast.showToast(
        msg: "logout success",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
        backgroundColor: Colors.green,
        textColor: Colors.white,
      );
    } finally {
      isLoading = false;
    }
  }
  
  @action
  Future<bool> updateUserInfo({String? nickname, String? avatar, String? sign}) async {
    isLoading = true;
    try {  
      // 创建更新后的用户对象
      final updatedUser = User(
        id: currentUser!.id,
        username: currentUser!.username,
        password: currentUser!.password,
        nickname: nickname ?? currentUser!.nickname,
        avatar: avatar ?? currentUser!.avatar,
        sign: sign ?? currentUser!.sign,
      );
      
      // 更新用户信息
      final success = await UserService.updateUserInfo(updatedUser);
      if (success) {
        currentUser = updatedUser;
        Fluttertoast.showToast(
          msg: "update success",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          backgroundColor: Colors.green,
          textColor: Colors.white,
        );
        return true;
      } else {
        Fluttertoast.showToast(
          msg: "update failed",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          backgroundColor: Colors.red,
          textColor: Colors.white,
        );
        return false;
      }
    } finally {
      isLoading = false;
    }
  }
  
  @action
  Future<bool> deleteAccount() async {
    isLoading = true;
    try {
      final success = await UserService.deleteAccount(currentUser!.id);
      if (success) {
        currentUser = null;
        Fluttertoast.showToast(
          msg: "account deleted",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          backgroundColor: Colors.green,
          textColor: Colors.white,
        );
        return true;
      } else {
        Fluttertoast.showToast(
          msg: "delete account failed",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          backgroundColor: Colors.red,
          textColor: Colors.white,
        );
        return false;
      }
    } finally {
      isLoading = false;
    }
  }
} 